using SheLife.Application.Interfaces;
using SheLife.Domain.Entities;
using SheLife.Domain.Interfaces;

namespace SheLife.Application.Services
{
    /// <summary>
    /// 习惯记录服务实现
    /// </summary>
    public class HabitRecordService : IHabitRecordService
    {
        private readonly IUnitOfWork _unitOfWork;

        public HabitRecordService(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        /// <summary>
        /// 根据ID获取习惯记录
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <returns>习惯记录实体</returns>
        public async Task<HabitRecord?> GetHabitRecordByIdAsync(Guid id)
        {
            return await _unitOfWork.HabitRecordRepository.GetByIdAsync(id);
        }

        /// <summary>
        /// 获取用户的所有习惯记录
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>习惯记录列表</returns>
        public async Task<IEnumerable<HabitRecord>> GetHabitRecordsByUserIdAsync(Guid userId)
        {
            var allRecords = await _unitOfWork.HabitRecordRepository.GetAllAsync();
            return allRecords.Where(r => r.UserId == userId).OrderByDescending(r => r.RecordDate);
        }

        /// <summary>
        /// 获取用户指定习惯的记录
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="habitId">习惯ID</param>
        /// <returns>习惯记录列表</returns>
        public async Task<IEnumerable<HabitRecord>> GetHabitRecordsByHabitIdAsync(Guid userId, Guid habitId)
        {
            var allRecords = await _unitOfWork.HabitRecordRepository.GetAllAsync();
            return allRecords.Where(r => r.UserId == userId && r.HabitId == habitId)
                             .OrderByDescending(r => r.RecordDate);
        }

        /// <summary>
        /// 获取用户指定日期的习惯记录
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="recordDate">记录日期</param>
        /// <returns>习惯记录列表</returns>
        public async Task<IEnumerable<HabitRecord>> GetHabitRecordsByDateAsync(Guid userId, DateTime recordDate)
        {
            var allRecords = await _unitOfWork.HabitRecordRepository.GetAllAsync();
            return allRecords.Where(r => r.UserId == userId && r.RecordDate.Date == recordDate.Date)
                             .OrderBy(r => r.RecordDate);
        }

        /// <summary>
        /// 获取用户指定日期范围的习惯记录
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <returns>习惯记录列表</returns>
        public async Task<IEnumerable<HabitRecord>> GetHabitRecordsByDateRangeAsync(Guid userId, DateTime startDate, DateTime endDate)
        {
            var allRecords = await _unitOfWork.HabitRecordRepository.GetAllAsync();
            return allRecords.Where(r => r.UserId == userId && r.RecordDate >= startDate && r.RecordDate <= endDate)
                             .OrderBy(r => r.RecordDate);
        }

        /// <summary>
        /// 创建习惯记录
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="habitId">习惯ID</param>
        /// <param name="recordDate">记录日期</param>
        /// <param name="isCompleted">完成状态</param>
        /// <param name="notes">备注</param>
        /// <returns>习惯记录实体</returns>
        public async Task<HabitRecord> CreateHabitRecordAsync(Guid userId, Guid habitId, DateTime recordDate, bool isCompleted = false, string? notes = null)
        {
            // 验证用户是否存在
            var user = await _unitOfWork.UserRepository.GetByIdAsync(userId);
            if (user == null || user.IsDeleted)
            {
                throw new ArgumentException("用户不存在");
            }

            // 验证习惯是否存在且属于该用户
            var habit = await _unitOfWork.HabitRepository.GetByIdAsync(habitId);
            if (habit == null || habit.UserId != userId)
            {
                throw new ArgumentException("习惯不存在或不属于当前用户");
            }

            // 检查是否已有同一天的记录
            var existingRecords = await GetHabitRecordsByDateAsync(userId, recordDate);
            var existingRecord = existingRecords.FirstOrDefault(r => r.HabitId == habitId);
            
            if (existingRecord != null)
            {
                // 如果已有记录，则更新它
                if (isCompleted)
                {
                    existingRecord.MarkAsCompleted(notes);
                }
                else
                {
                    existingRecord.MarkAsIncomplete();
                }
                
                await _unitOfWork.HabitRecordRepository.UpdateAsync(existingRecord);
                await _unitOfWork.SaveChangesAsync();
                
                return existingRecord;
            }

            // 创建新记录
            var habitRecord = HabitRecord.Create(userId, habitId, recordDate, isCompleted, notes);

            await _unitOfWork.HabitRecordRepository.AddAsync(habitRecord);
            await _unitOfWork.SaveChangesAsync();

            return habitRecord;
        }

        /// <summary>
        /// 标记习惯记录为完成
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <param name="notes">备注</param>
        /// <returns>习惯记录实体</returns>
        public async Task<HabitRecord?> MarkHabitRecordAsCompletedAsync(Guid id, string? notes = null)
        {
            var habitRecord = await _unitOfWork.HabitRecordRepository.GetByIdAsync(id);
            if (habitRecord == null)
            {
                return null;
            }

            habitRecord.MarkAsCompleted(notes);
            await _unitOfWork.HabitRecordRepository.UpdateAsync(habitRecord);
            await _unitOfWork.SaveChangesAsync();

            return habitRecord;
        }

        /// <summary>
        /// 标记习惯记录为未完成
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <returns>习惯记录实体</returns>
        public async Task<HabitRecord?> MarkHabitRecordAsIncompleteAsync(Guid id)
        {
            var habitRecord = await _unitOfWork.HabitRecordRepository.GetByIdAsync(id);
            if (habitRecord == null)
            {
                return null;
            }

            habitRecord.MarkAsIncomplete();
            await _unitOfWork.HabitRecordRepository.UpdateAsync(habitRecord);
            await _unitOfWork.SaveChangesAsync();

            return habitRecord;
        }

        /// <summary>
        /// 更新习惯记录备注
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <param name="notes">备注</param>
        /// <returns>习惯记录实体</returns>
        public async Task<HabitRecord?> UpdateHabitRecordNotesAsync(Guid id, string? notes)
        {
            var habitRecord = await _unitOfWork.HabitRecordRepository.GetByIdAsync(id);
            if (habitRecord == null)
            {
                return null;
            }

            habitRecord.UpdateNotes(notes);
            await _unitOfWork.HabitRecordRepository.UpdateAsync(habitRecord);
            await _unitOfWork.SaveChangesAsync();

            return habitRecord;
        }

        /// <summary>
        /// 删除习惯记录
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <returns>是否成功</returns>
        public async Task<bool> DeleteHabitRecordAsync(Guid id)
        {
            var habitRecord = await _unitOfWork.HabitRecordRepository.GetByIdAsync(id);
            if (habitRecord == null)
            {
                return false;
            }

            await _unitOfWork.HabitRecordRepository.DeleteAsync(id);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }
    }
}